package cn.wolfcode.ssm.shiro;

import cn.wolfcode.ssm.domain.User;
import cn.wolfcode.ssm.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("myRealm")
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    // 强势将父类的密码匹配器注入md5解析方式
    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if ("admin".equals(user.getUsername())) {
            info.addRole("admin");
            info.addStringPermission("*:*");
        }else{
            List<String> roleSns = userService.getRoleSnsByEmployeeId(user.getId());
            List<String> permissionExps = userService.getPermissionExpsByEmployeeId(user.getId());
            info.addRoles(roleSns);
            info.addStringPermissions(permissionExps);
        }

        return info;
    }

    // 登录验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();

        User user = userService.getUserByUsername(username);
        if(user == null){
            return null;
        }

        return new SimpleAuthenticationInfo(user, user.getPassword(),
                ByteSource.Util.bytes("admin"), "myRealm");
    }
}
